package com.puboot.module.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.puboot.common.util.CoreConst;
import com.puboot.common.util.Pagination;
import com.puboot.exception.ArticleNotFoundException;
import com.puboot.module.admin.model.BizArticle;
import com.puboot.module.admin.model.BizCategory;
import com.puboot.module.admin.service.BizArticleService;
import com.puboot.module.admin.service.BizCategoryService;
import com.puboot.module.admin.service.BizThemeService;
import com.puboot.module.admin.vo.ArticleConditionVo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * CMS页面相关接口
 *
 * @author Linzhaoguan
 * @version V1.0
 * @date 2019年9月11日
 */
@Controller
@AllArgsConstructor
public class BlogWebController {

    private static final String THEME_PREFIX = "theme/";

    private final BizArticleService bizArticleService;
    private final BizCategoryService categoryService;
    private final BizThemeService bizThemeService;

    /**
     * 首页
     *
     * @param model
     * @param vo
     * @return
     */
    @GetMapping("/")
    public String index(Model model, ArticleConditionVo vo) {
        //pblog模板
        model.addAttribute("pageUrl", "blog/index");
        model.addAttribute("categoryId", "index");
        model.addAttribute("sliderList", bizArticleService.sliderList());//轮播文章
        loadMainPage(model, vo);

        // shuili模板
        loadIndexPage(model);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
    }

    /**
     * 文章列表分页
     *
     * @param pageNumber
     * @param vo
     * @param model
     * @return
     */
    @RequestMapping("/blog/index/{pageNumber}")
    public String index(@PathVariable("pageNumber") Integer pageNumber, ArticleConditionVo vo, Model model) {
        vo.setPageNumber(pageNumber);
        model.addAttribute("pageUrl", "blog/index");
        model.addAttribute("categoryId", "index");
        loadMainPage(model, vo);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
    }

    /**
     * 分类列表
     *
     * @param categoryId
     * @param model
     * @return
     */
    @GetMapping("/blog/category/{categoryId}")
    public String category(@PathVariable("categoryId") Integer categoryId, Model model) {
        ArticleConditionVo vo = new ArticleConditionVo();
//        vo.setCategoryId(categoryId);
        model.addAttribute("pageUrl", "blog/category/" + categoryId);
//        model.addAttribute("categoryId", categoryId);
//        loadMainPage(model, vo);
        loadListPage(model, categoryId, vo);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/list";
    }

//    @GetMapping("/blog/category/{categoryId}")
//    public String category(@PathVariable("categoryId") Integer categoryId, Model model) {
//        ArticleConditionVo vo = new ArticleConditionVo();
//        vo.setCategoryId(categoryId);
//        model.addAttribute("pageUrl", "blog/category/" + categoryId);
//        model.addAttribute("categoryId", categoryId);
//        loadMainPage(model, vo);
//        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
//    }

    @GetMapping("/blog/category/{categoryId}/{pageNumber}")
    public String category(@PathVariable("categoryId") Integer categoryId, @PathVariable("pageNumber") Integer pageNumber, Model model) {
        ArticleConditionVo vo = new ArticleConditionVo();
//        vo.setCategoryId(categoryId);
        vo.setPageNumber(pageNumber);
        model.addAttribute("pageUrl", "blog/category/" + categoryId);
//        model.addAttribute("categoryId", categoryId);
//        loadMainPage(model, vo);
        loadListPage(model, categoryId, vo);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/list";
    }

//    @GetMapping("/blog/category/{categoryId}/{pageNumber}")
//    public String category(@PathVariable("categoryId") Integer categoryId, @PathVariable("pageNumber") Integer pageNumber, Model model) {
//        ArticleConditionVo vo = new ArticleConditionVo();
//        vo.setCategoryId(categoryId);
//        vo.setPageNumber(pageNumber);
//        model.addAttribute("pageUrl", "blog/category/" + categoryId);
//        model.addAttribute("categoryId", categoryId);
//        loadMainPage(model, vo);
//        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
//    }


    /**
     * 标签列表
     *
     * @param tagId
     * @param model
     * @return
     */
    @GetMapping("/blog/tag/{tagId}")
    public String tag(@PathVariable("tagId") Integer tagId, Model model) {
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setTagId(tagId);
        model.addAttribute("pageUrl", "blog/tag/" + tagId);
        loadMainPage(model, vo);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
    }

    /**
     * 标签列表（分页）
     *
     * @param tagId
     * @param pageNumber
     * @param model
     * @return
     */
    @GetMapping("/blog/tag/{tagId}/{pageNumber}")
    public String tag(@PathVariable("tagId") Integer tagId, @PathVariable("pageNumber") Integer pageNumber, Model model) {
        ArticleConditionVo vo = new ArticleConditionVo();
        vo.setTagId(tagId);
        vo.setPageNumber(pageNumber);
        model.addAttribute("pageUrl", "blog/tag/" + tagId);
        loadMainPage(model, vo);
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/index";
    }

    /**
     * 文章详情
     *
     * @param model
     * @param articleId
     * @return
     */
    @GetMapping("/blog/article/{articleId}")
    public String article(HttpServletRequest request, Model model, @PathVariable("articleId") Integer articleId) {
        BizArticle article = bizArticleService.selectById(articleId);
        if (article == null || CoreConst.STATUS_INVALID.equals(article.getStatus())) {
            throw new ArticleNotFoundException();
        }
        model.addAttribute("article", article);
//        model.addAttribute("categoryId", article.getCategoryId());
        loadArticlePage(model, article.getCategoryId());
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/article";
    }

    /**
     * 评论
     *
     * @param model
     * @return
     */
    @GetMapping("/blog/comment")
    public String comment(Model model) {
        model.addAttribute("categoryId", "comment");
        return THEME_PREFIX + bizThemeService.selectCurrent().getName() + "/comment";
    }

    private void loadArticlePage(Model model, Integer categoryId) {
        //左侧分类列表
        List<BizCategory> catelist = new ArrayList<>();
        Integer cId = null;
        BizCategory category = null;

        BizCategory category1 = categoryService.selectById(categoryId);

        List<BizCategory> childrenlist = categoryService.selectByPid(categoryId);
        if(childrenlist == null || childrenlist.size() == 0) {      // 如果没有子栏目，则显示root级别的栏目
            BizCategory bizCategory = new BizCategory();
            bizCategory.setStatus(CoreConst.STATUS_VALID);
            bizCategory.setPid(0);
            List<BizCategory> clist = categoryService.selectCategories(bizCategory);
            catelist.addAll(clist);
            cId = categoryId;                                       //
            category = category1;

        } else {
            catelist.addAll(childrenlist);                          // 如果有子栏目，则显示子栏目列表
            category = childrenlist.get(0);
            cId = category.getId();
        }

        model.addAttribute("cateList", catelist);
        model.addAttribute("categoryId", cId);
        model.addAttribute("categoryName", category.getName());

    }

    private void loadListPage(Model model, Integer categoryId, ArticleConditionVo vo) {
        //左侧分类列表
        List<BizCategory> catelist = new ArrayList<>();
        Integer cId = null;
        BizCategory category = null;


        BizCategory category1 = categoryService.selectById(categoryId);

        List<BizCategory> childrenlist = categoryService.selectByPid(categoryId);
        if(childrenlist == null || childrenlist.size() == 0) {      // 如果没有子栏目，则显示root级别的栏目
            BizCategory bizCategory = new BizCategory();
            bizCategory.setStatus(CoreConst.STATUS_VALID);
            bizCategory.setPid(0);
            List<BizCategory> clist = categoryService.selectCategories(bizCategory);
            catelist.addAll(clist);
            cId = categoryId;                                       //
            category = category1;

        } else {
            catelist.addAll(childrenlist);                          // 如果有子栏目，则显示子栏目列表
            category = childrenlist.get(0);
            cId = category.getId();
        }

        vo.setCategoryId(cId);
        vo.setStatus(CoreConst.STATUS_VALID);
        IPage<BizArticle> page = new Pagination<>(vo.getPageNumber(), vo.getPageSize());
        List<BizArticle> articleList = bizArticleService.findByCondition(page, vo);

        model.addAttribute("page", page);
        model.addAttribute("cateList", catelist);
        model.addAttribute("categoryId", cId);
        model.addAttribute("articleList", articleList);//文章列表
        model.addAttribute("categoryName", category.getName());
    }

    private void loadIndexPage(Model model) {
        int categoryId1 = 8;
        List<BizArticle> articleList1 = bizArticleService.selectByCategoryId(categoryId1, 6);
        BizCategory category1 = categoryService.getById(categoryId1);
        loadPage(model, "category1", category1.getName()
                , "view1", articleList1
                , "cateId1", categoryId1);

        int categoryId2 = 7;
        List<BizArticle> articleList2 = bizArticleService.selectByCategoryId(categoryId2, 6);
        BizCategory category2 = categoryService.getById(categoryId2);
        loadPage(model, "category2", category2.getName()
                , "view2", articleList2
                , "cateId2", categoryId2);

        int categoryId3 = 6;
        List<BizArticle> articleList3 = bizArticleService.selectByCategoryId(categoryId3, 6);
        BizCategory category3 = categoryService.getById(categoryId3);
        loadPage(model, "category3", category3.getName()
                , "view3", articleList3
                , "cateId3", categoryId3);

        int categoryId4 = 4;
        List<BizArticle> articleList4 = bizArticleService.selectByCategoryId(categoryId4, 6);
        BizCategory category4 = categoryService.getById(categoryId4);
        loadPage(model, "category4", category4.getName()
                , "view4", articleList4
                , "cateId4", categoryId4);

        int categoryId5 = 3;
        List<BizArticle> articleList5 = bizArticleService.selectByCategoryId(categoryId5, 6);
        BizCategory category5 = categoryService.getById(categoryId5);
        loadPage(model, "category5", category5.getName()
                , "view5", articleList5
                , "cateId5", categoryId5);

        int categoryId6 = 2;
        List<BizArticle> articleList6 = bizArticleService.selectByCategoryId(categoryId6, 6);
        BizCategory category6 = categoryService.getById(categoryId6);
        loadPage(model, "category6", category6.getName()
                , "view6", articleList6
                , "cateId6", categoryId6);
    }

    private void loadPage(Model model, String categoryIndexName, String categoryName
            , String viewIndexName, List<BizArticle> list
            , String categoryIdName, Integer categoryId) {
        model.addAttribute(viewIndexName, list);
        model.addAttribute(categoryIndexName, categoryName);
        model.addAttribute(categoryIdName, categoryId);
    }

    private void loadMainPage(Model model, ArticleConditionVo vo) {
        vo.setStatus(CoreConst.STATUS_VALID);
        IPage<BizArticle> page = new Pagination<>(vo.getPageNumber(), vo.getPageSize());
        List<BizArticle> articleList = bizArticleService.findByCondition(page, vo);
        model.addAttribute("page", page);
        model.addAttribute("articleList", articleList);//文章列表
        if (vo.getCategoryId() != null) {
            BizCategory category = categoryService.getById(vo.getCategoryId());
            if (category != null) {
                model.addAttribute("categoryName", category.getName());
            }
        }
    }

}
